#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File  :zi_main_provision.py
# Time  :2025/5/16 16:40
# Email :fortunatedong@163.com
# Author:by Adonli
import os
import shutil
import time
from datetime import datetime, timedelta

import schedule
import toml
from config import ROOT_DIR
from utils.business_task.continued_provision import ContinuedProvision
from settings.kinslot_email import EmailSender, zi_send_email
class ZiMainProvision():
    def zi_main_provision(self):
        configs_toml = os.path.join(ROOT_DIR, 'settings', 'configs.toml')
        provision_excel_file_dir_path = os.path.join(ROOT_DIR, 'Datas/business_continued_provision/zi_provision_file_temp',)
        success_mail_provision_dir_path = os.path.join(ROOT_DIR, 'Datas/business_continued_provision/zi_success_email_provision_file',)

        now_date = datetime.now().strftime('%Y-%m-%d')
        # ===============================================
        # date_obj = datetime.strptime(now_date, '%Y-%m-%d')
        # now_date = (date_obj - timedelta(days=2)).strftime('%Y-%m-%d')
        # ===============================================
        ContinuedProvision("Y:/理光报备子公司汇总表.xlsx",now_date,'zi').provision_read_infoamtion()

        # success_mail_provision_file_names是用来进行同一天对比邮件附件是否重复
        success_mail_provision_file_names = [
            entry.name for entry in os.scandir(success_mail_provision_dir_path)
            if entry.is_file()
        ]
        # print(success_mail_provision_file_names)
        with open(configs_toml, "r", encoding="utf-8") as f:
            cfg = toml.load(f)

        # provision_file_name_list是当天需要发送邮件附件的文件名列表，每一次监控结果都会刷新列表
        provision_file_name_list = cfg['BUSINESS']['ZiProcisionFileNameList']
        print(provision_file_name_list)
        if provision_file_name_list:
            for provision_file_name in provision_file_name_list:
                if provision_file_name not in success_mail_provision_file_names:
                    source_file = os.path.join(provision_excel_file_dir_path, provision_file_name)
                    destination_file = os.path.join(success_mail_provision_dir_path, provision_file_name)
                    zi_send_email(source_file,provision_file_name,now_date)

                    # Copy file to success directory after successful email send
                    shutil.copy2(source_file, destination_file)
                    print(f"{provision_file_name}已保存至success_email_provision_file文件夹下")
                else:
                    print(f'{provision_file_name}已发送邮件')

def run_pantum_alert():
    """检查当前时间是否在8:00-20:00之间，如果是则执行任务"""
    now = datetime.now().time()
    starttime = datetime.strptime('08:00', '%H:%M').time()
    endtime = datetime.strptime('20:00', '%H:%M').time()

    if starttime <= now <= endtime:
        print(f"{datetime.now().strftime('%H:%M')} 正在执行续报备检查...")
        zi = ZiMainProvision()
        return zi.zi_main_provision()
    else:
        print(f"{datetime.now().strftime('%H:%M')} 当前时间不在工作时段(8:00-20:00)")
        return None


if __name__ == '__main__':
    print("启动Pantum工单监控系统...")

    # 立即运行一次（如果当前时间在8:00-20:00之间）
    run_pantum_alert()

    # 设置定时任务（每30分钟运行一次）
    schedule.every(30).minutes.do(run_pantum_alert)

    # 保持主程序运行
    while True:
        schedule.run_pending()
        time.sleep(60)  # 每分钟检查一次，减少CPU占用



